import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {UserDetailService} from './user-detail.service';
import {CustomValidators} from '@kylin/validators';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'kylin-user-manager-detail',
    templateUrl: './user-detail.component.html',
    styleUrls: ['../reset-password/reset-password.component.less']
})
export class UserDetailComponent implements OnInit {
    @Input() isVisible = false;
    @Input() userInfo: any;
    @Input() curUser: any;
    @Input() roleName: string;
    @Output() isVisibleChange = new EventEmitter<boolean>();
    @Output() processRstChange = new EventEmitter<boolean>();
    title: string;
    loading = false;
    userForm: FormGroup;

    editMode = false;
    roles: any;
    sexs: any;
    types: any;
    enableds: any;

    username = '';
    nickname = '';

    constructor(private usersve: UserDetailService, private fb: FormBuilder, private message: NzMessageService) {
    }

    ngOnInit() {
        const userInfo = this.userInfo || {};
        this.editMode = !!this.userInfo;
        this.title = this.editMode ? '修改用户信息' : '添加用户';
        this.roles = this.usersve.getRole();
        this.sexs = this.usersve.getSex();
        this.types = this.usersve.getType();
        this.enableds = this.usersve.getEnabled();
        const role = userInfo.role === '普通用户' ? 'USER' :
            (userInfo.role === '草地管理员' ? 'GRASSLAND_ADMIN' :
                (userInfo.role === '林地管理员' ? 'FOREST_ADMIN' : 'CULTIVATION_ADMIN'));
        const sex = userInfo.sex === '男' ? 1 : 2;
        const type = userInfo.type === '草地' ? 1 : (userInfo.type === '耕地' ? 2 : (userInfo.type === '林地' ? 3 : 4));
        const enabled = userInfo.enabled === '启用';
        this.userForm = this.fb.group({
            role: [this.editMode ? role : this.roles[0].value],
            username: [this.editMode ? userInfo.username : this.username],
            nickname: [this.editMode ? userInfo.nickname : this.nickname],
            password: ['', CustomValidators.passwordValidator()],
            rePassword: ['', CustomValidators.passwordValidator()],
            sex: [this.editMode ? sex : 1],
            phone: [userInfo.phone || '', [Validators.required, CustomValidators.phoneNumberValidator]],
            enabled: [this.editMode ? enabled : this.enableds[0].value],
            type: [this.editMode ? type : this.types[0].value]
        });
    }

    checkInput() {
        let {password, rePassword, role, type, username, nickname, sex, phone, enabled} = this.userForm.value;
        password = (password || '').trim();
        rePassword = (rePassword || '').trim();
        role = (role || '');
        type = (type || '');
        username = (username || '').trim();
        nickname = (nickname || '').trim();
        phone = (phone || '').trim();
        sex = (sex || '');
        if (!username) {
            return '请输入用户名'
        }
        if (!nickname) {
            return '请输入用户昵称'
        }
        if (!phone) {
            return '请输入手机号'
        } else if (!CustomValidators.checkPhone(phone)) {
            return '请输入正确格式的手机号码'
        }
        if (!this.editMode) {
            if (!password || !rePassword) {
                return '请输入密码或确认密码';
            } else if (this.userForm.get('password').errors || this.userForm.get('rePassword').errors) {
                return '请输入正确格式的密码，密码由8-16位大写、小写字母，数字和特殊字符中的三种或四种组成'
            } else if (password !== rePassword) {
                return '两次输入密码不一致，请重新输入';
            }
        }
        if (!role) {
            return '请选择用户角色'
        }
        if (!type) {
            return '请选择用户类型'
        }
        if (!sex) {
            return '请选择用户性别'
        }
    }

    // 关闭弹框
    closeModal(processRstChange?: boolean) {
        this.isVisible = false;
        this.isVisibleChange.emit(false);
        this.processRstChange.emit(processRstChange)
    }

    // 确认提交表单
    submit() {
        const checkRst = this.checkInput();
        if (checkRst) {
            this.message.warning(checkRst);
            return;
        }
        this.loading = true;
        if (this.editMode) {
            this.userForm.value.id = this.userInfo.id;
        }

        this.usersve.addUser(this.userForm.value).then(rep => {
            if (rep.resp_code === '10000') {
                this.message.success(this.editMode ? `修改用户 ${this.userForm.get('username').value} 成功` : `添加用户 ${this.userForm.get('username').value} 成功`);
                this.closeModal(true);
            } else {
                this.message.error(this.editMode ? `修改用户失败，${rep.resp_msg}` : `添加用户失败，${rep.resp_msg}`);
            }
            this.loading = false;
        })
    }
}
